package com.yanchangapp.ui.activity.purchase.contract;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.luck.picture.lib.decoration.RecycleViewDivider;
import com.luck.picture.lib.tools.ScreenUtils;
import com.yanchangapp.PsCreateListAdapter;
import com.yanchangapp.R;
import com.yanchangapp.commom.LoadingType;
import com.yanchangapp.model.bean.CnProductBean;
import com.yanchangapp.model.bean.OrderProductBean;
import com.yanchangapp.model.bean.ProductExtractBean;
import com.yanchangapp.model.response.ContractDetailResponse;
import com.yanchangapp.ui.activity.purchase.ProductNormalExtActivity;
import com.yanchangapp.ui.presenter.ContractEditAtPresenter;
import com.yanchangapp.ui.view.ContractEditAtView;
import com.yanchangapp.widget.GoodsPriceDialog;
import com.yanchangapp.widget.LikeContentDialog;
import com.yanchangapp.widget.SpannableMoney;
import com.zxl.baselib.ui.base.BaseActivity;
import com.zxl.baselib.util.formatter.BigDecimalUtils;
import com.zxl.baselib.util.time.TimeUtil;
import com.zxl.baselib.util.ui.ResHelper;
import com.zxl.baselib.util.ui.UIUtils;
import com.zxl.baselib.widget.NiceNestedScrollView;
import com.zxl.baselib.widget.YCLoadingView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 合同修改的活动
 */
public class ContractEditActivity extends BaseActivity<ContractEditAtView, ContractEditAtPresenter> implements ContractEditAtView, PsCreateListAdapter.ITotalAmountChanged {
    @BindView(R.id.ivToolbarNavigation)
    ImageView ivToolbarNavigation;
    @BindView(R.id.vToolbarDivision)
    View vToolbarDivision;
    @BindView(R.id.tvToolbarTitle)
    TextView tvToolbarTitle;
    @BindView(R.id.ibAddMenu)
    ImageButton ibAddMenu;
    @BindView(R.id.tvProductSum)
    TextView tvProductSum;
    @BindView(R.id.bottom)
    RelativeLayout bottom;
    @BindView(R.id.tvSignTimeTitle)
    TextView tvSignTimeTitle;
    @BindView(R.id.tvSignTime)
    TextView tvSignTime;
    @BindView(R.id.tvBuyerTitle)
    TextView tvBuyerTitle;
    @BindView(R.id.tvBuyerName)
    TextView tvBuyerName;
    @BindView(R.id.tvSupplierTitle)
    TextView tvSupplierTitle;
    @BindView(R.id.tvSupplierName)
    TextView tvSupplierName;
    @BindView(R.id.rvProductList)
    RecyclerView rvProductList;
    @BindView(R.id.tvProductEmpty)
    TextView tvProductEmpty;
    @BindView(R.id.tvTitleStartTime)
    TextView tvTitleStartTime;
    @BindView(R.id.ivStartArrow)
    ImageView ivStartArrow;
    @BindView(R.id.rlClause)
    RelativeLayout rlClause;
    @BindView(R.id.scrollContent)
    NiceNestedScrollView scrollContent;
    @BindView(R.id.btnNextRefresh)
    TextView btnNextRefresh;
    @BindView(R.id.llErrorNetwork)
    LinearLayout llErrorNetwork;
    @BindView(R.id.ycLoading)
    YCLoadingView ycLoading;
    @BindView(R.id.tvChooseProduct)
    TextView tvChooseProduct;
    @BindView(R.id.btnApprove)
    Button btnApprove;
    private String id,supplierId;
    private static final String ID = "id";

    private String innerClause = "";
    private PsCreateListAdapter mPsCreateListAdapter;
    private List<ProductExtractBean> mExtractBeanList = new ArrayList<>();
    private double totalMoney;
    private EditText etNum;
    private Dialog mSingleDialog;
    private static final int REQUEST_PRODUCT_CODE = 0x0098;
    @Override
    protected void init() {
        if (null == getIntent() || !getIntent().hasExtra(ID)){
            finish();
        }else {
            id = getIntent().getStringExtra(ID);
        }
    }

    public static void show(Activity activity, String id) {
        Intent intent = new Intent(activity, ContractEditActivity.class);
        intent.putExtra(ID, id);
        activity.startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            if (requestCode == ClauseEditActivity.CODE_QUERY_CLAUSE){
                innerClause = data.getStringExtra("data");
            }else if (requestCode == REQUEST_PRODUCT_CODE){
                mExtractBeanList.clear();
                mExtractBeanList.addAll((List<ProductExtractBean>)data.getExtras().getSerializable("data"));
                mPsCreateListAdapter.notifyDataSetChanged();
                if (tvProductEmpty.getVisibility() == View.VISIBLE){
                    tvProductEmpty.setVisibility(View.GONE);
                }

                if (rvProductList.getVisibility() == View.GONE){
                    rvProductList.setVisibility(View.VISIBLE);
                }
                setSumText();
            }
        }
    }

    private void showSetPriceDialog(Context context, int position, double price) {
        mSingleDialog = new GoodsPriceDialog.Builder(context)
                .setPrice(price)
                .setEnsureListener(new GoodsPriceDialog.PriceEnsureListener() {
                    @Override
                    public void onEnsureClick(double _price) {
                        mExtractBeanList.get(position).setPrice(_price);
                        mPsCreateListAdapter.notifyItemChanged(position);
                        setSumText();
                        mSingleDialog.dismiss();
                    }
                }).build();
        mSingleDialog.show();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_contract_edit;
    }

    @Override
    protected ContractEditAtPresenter createPresenter() {
        return new ContractEditAtPresenter(this);
    }

    private void setLoadingState(LoadingType loadingType){
        switch (loadingType){
            case LOADING:
                if (ycLoading.getVisibility() == View.GONE){
                    ycLoading.setVisibility(View.VISIBLE);
                }

                if (scrollContent.getVisibility() == View.VISIBLE){
                    scrollContent.setVisibility(View.GONE);
                    bottom.setVisibility(View.GONE);
                }

                if (llErrorNetwork.getVisibility() == View.VISIBLE){
                    llErrorNetwork.setVisibility(View.GONE);
                }
                break;
            case SUCCESS:

                if (ycLoading.getVisibility() == View.VISIBLE){
                    ycLoading.setVisibility(View.GONE);
                }

                if (scrollContent.getVisibility() == View.GONE){
                    scrollContent.setVisibility(View.VISIBLE);
                    bottom.setVisibility(View.VISIBLE);
                }


                if (llErrorNetwork.getVisibility() == View.VISIBLE){
                    llErrorNetwork.setVisibility(View.GONE);
                }
                break;
            case ERROR:
                if (ycLoading.getVisibility() == View.VISIBLE){
                    ycLoading.setVisibility(View.GONE);
                }

                if (scrollContent.getVisibility() == View.VISIBLE){
                    scrollContent.setVisibility(View.GONE);
                    bottom.setVisibility(View.GONE);
                }


                if (llErrorNetwork.getVisibility() == View.GONE){
                    llErrorNetwork.setVisibility(View.VISIBLE);
                }
                break;
            default:
                break;
        }
    }

    // 设置商品总量
    private void setSumText(){
        String totalMoney = BigDecimalUtils.keep2Decimal(calculateNum());
        int len = totalMoney.length();
        SpannableString spannableString = new SpannableString(ResHelper.getString(R.string.down_order_sum,
                String.valueOf(mExtractBeanList.size()),totalMoney));
        int totalLength = spannableString.length();
        spannableString.setSpan(new SpannableMoney(this),
                totalLength-len-1,totalLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvProductSum.setText(spannableString);
    }

    private double calculateNum(){
        double sum = 0;
        for (int i=0;i<mExtractBeanList.size();i++){
            ProductExtractBean bean = mExtractBeanList.get(i);
            sum += bean.getPrice() * bean.getSelectSize();
        }
        totalMoney = sum;
        return sum;
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        tvToolbarTitle.setText("修改合同");
        initAdapter();
    }

    private void initAdapter() {
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        manager.setSmoothScrollbarEnabled(true);
        manager.setAutoMeasureEnabled(true);
        rvProductList.setHasFixedSize(true);
        rvProductList.setNestedScrollingEnabled(false);
        rvProductList.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, ScreenUtils.dip2px(this, 0.5f),
                ContextCompat.getColor(this, R.color.borderColorBase)));
        rvProductList.setLayoutManager(manager);
        mPsCreateListAdapter = new PsCreateListAdapter(R.layout.item_ps_create_list,mExtractBeanList);
        mPsCreateListAdapter.setITotalAmountChanged(this);
        // 设置adapter...
        rvProductList.setAdapter(mPsCreateListAdapter);
    }

    @Override
    protected void initData() {
        setLoadingState(LoadingType.LOADING);
        mPresenter.queryContractDetail(id);
    }

    @Override
    protected void initListener() {
        ivToolbarNavigation.setOnClickListener(v -> finish());


        btnNextRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initData();
            }
        });

        btnApprove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkDataWithSubmit();
            }
        });

        tvChooseProduct.setOnClickListener(v -> ProductNormalExtActivity.show(ContractEditActivity.this,
                supplierId
               ,mExtractBeanList));

        // 合同条款点击事件...
        rlClause.setOnClickListener(v -> ClauseEditActivity.show(ContractEditActivity.this,innerClause));

        mPsCreateListAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.ivDelete){
                mExtractBeanList.remove(position);
                mPsCreateListAdapter.notifyItemRemoved(position);
                mPsCreateListAdapter.notifyItemRangeChanged(position, mExtractBeanList.size() - position);
                setSumText();
                if (mExtractBeanList.size() == 0){
                    tvProductEmpty.setVisibility(View.VISIBLE);
                    rvProductList.setVisibility(View.GONE);
                }
            }else if (view.getId() == R.id.ivEdit || view.getId() == R.id.tvSinglePrice){
                showSetPriceDialog(ContractEditActivity.this,
                        position,
                        mExtractBeanList.get(position).getPrice());
            }
        });
    }

    private void checkDataWithSubmit() {
        if (mExtractBeanList.size() == 0){
            UIUtils.showToast("请进行品种选择");
            return;
        }

        List<CnProductBean> mProductLists = new ArrayList<>();
        for (int i=0;i<mExtractBeanList.size();i++){
            ProductExtractBean bean = mExtractBeanList.get(i);
            mProductLists.add(new CnProductBean(
                    bean.getProductId(),bean.getProductNo(),bean.getSelectSize(),bean.getPrice(),
                    bean.getPrice() * bean.getSelectSize()));
        }
        mPresenter.editContract(id, totalMoney,mProductLists,innerClause);
    }

    @Override
    public void editContractSuccess(String id) {
        mRxManager.post(ContractListActivity.REFRESH_CONTRACT_LIST,true);
        ContractEnsureActivity.show(ContractEditActivity.this,id);
    }

    @Override
    public void editContractFailure(String err) {
        UIUtils.showToast(err);
    }

    @Override
    public void getContractDetailSuccess(ContractDetailResponse contractDetailResponse) {
        setLoadingState(LoadingType.SUCCESS);
        // 设置基本信息 用户等
        tvSignTime.setText(TimeUtil.getDayTime(contractDetailResponse.getCreateDate()));
        tvBuyerName.setText(contractDetailResponse.getPurName());
        tvSupplierName.setText(contractDetailResponse.getSupName());


        // 进行类型转换
        mExtractBeanList.clear();
        for (int i=0;i<contractDetailResponse.getProducts().size();i++){
            OrderProductBean orderProductBean = contractDetailResponse.getProducts().get(i);
            mExtractBeanList.add(new ProductExtractBean(
                    orderProductBean.getProductId(),
                    orderProductBean.getProductName(),
                    orderProductBean.getPrice(),
                    orderProductBean.getProductFormat(),
                    orderProductBean.getManufacturer(),
                    orderProductBean.getNotOrderNum(),
                    orderProductBean.getRegistratNoName(),
                    orderProductBean.getRegistratNo(),
                    orderProductBean.getProductNo(),
                    orderProductBean.getPurNum()
            ));
        }


        // 有数据可以考虑进行隐藏了
        if (mExtractBeanList.size() != 0){
            mPsCreateListAdapter.notifyDataSetChanged();
            tvProductEmpty.setVisibility(View.GONE);
        }
        // 设置数量...
        setSumText();
        supplierId = contractDetailResponse.getSupplycoId();
        // 合同条款信息
        innerClause = contractDetailResponse.getCovenant();
    }

    @Override
    public void getContractDetailFailure(String err) {
        setLoadingState(LoadingType.ERROR);
        UIUtils.showToast(err);
    }

    @Override
    public void justCalculateTotalPrice() {
        setSumText();
    }
}
